package com.xgp.labblog.controller;

import com.xgp.labblog.model.Msg;
import com.xgp.labblog.service.MsgService;
import com.xgp.labblog.tool.BadWordUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class messageController {

    @Autowired
    MsgService msgService;

    @GetMapping("/message")
    public String message(Model model,@RequestParam(value = "title",required=false,defaultValue = "") String title) {
        try {

            List<Msg> msgs = null;
            if(title.isEmpty()) {
                msgs = msgService.showMsg(10);
            }else {
                msgs = msgService.showMsgByTitle(10,title);
            }
            model.addAttribute("msgs",msgs);
            return "html/message";
        }catch (Exception e) {
            return "error/4xx";
        }

    }

    @GetMapping("/supper-msg/{id}")
    @ResponseBody
    public void supperWrite(@PathVariable(name = "id") Integer id) {

        msgService.addSupCount(id);
    }

    @PostMapping("/addMsg")
    @ResponseBody
    public void addMsg(String msg) {
        if(msg.isEmpty()) {
            return;
        }
        String newMsg = BadWordUtil2.replaceBadWord(msg, 2, "*");
        msgService.addMsg(newMsg);
    }
}
